/*
 * ConcurrentMessageQueue.h
 *
 *  Created on: Jul 22, 2013
 *      Author: m
 */

#ifndef CONCURRENTMESSAGEQUEUE_H_
#define CONCURRENTMESSAGEQUEUE_H_

#include "MessageQueue.h"
#include "MessageQueueInterface.h"

namespace communication
{

template <class T> class ConcurrentMessageQueue : public MessageQueueInterface<T>
{
protected:
    std::string m_name;
    MessageQueue<T> *m_mq;

public:

    ConcurrentMessageQueue() :
        m_name(),
        m_mq()
    {}

    ConcurrentMessageQueue( std::string name ) :
        m_name( name ),
        m_mq( new MessageQueue<T>( "/tmp/"+name ) )
    {
    }

    virtual ~ConcurrentMessageQueue()
    {
        this->close();
    }

    void put( const T &data )
    {
        m_mq->put( 1, data );
    }

    T get()
    {
        return m_mq->get( 1 );
    }

    bool poll( T& data )
    {
        return m_mq->poll( 1, data );
    }

    void open( std::string name )
    {
        if ( m_name != name )
        {
            this->close();

            m_mq = new MessageQueue<T>( "/tmp/" + name );
            m_name = name;
        }
    }

    void close()
    {
        if ( !m_name.empty() )
        {
            delete m_mq;
            m_name.clear();
        }
    }

    void destroy()
    {
        if ( m_mq )
        {
            m_mq->destroy();

            this->close();
        }
    }
};

} /* namespace communication */
#endif /* CONCURRENTMESSAGEQUEUE_H_ */
